package com.hserver.docker.task;

import cn.hserver.plugin.web.context.WebConstConfig;
import cn.hserver.plugin.web.handlers.Ws;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hserver.docker.bean.Msg;
import com.hserver.docker.controller.DataWebSocket;
import com.hserver.docker.service.LogService;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.ioc.annotation.Task;
import cn.hserver.core.server.context.ConstConfig;

import java.util.Iterator;
import java.util.Map;

@Bean
public class RecordTask {

    @Autowired
    private LogService logService;

    @Task(name = "定时返回给用户记录日志", time = "3000")
    public void task() {
        Map<String, Ws> da = DataWebSocket.wsMap;
        Iterator<String> iterator = da.keySet().iterator();
        while (iterator.hasNext()) {
            String recordId = iterator.next();
            Ws ws = DataWebSocket.wsMap.get(recordId);
            if (ws.getCtx().channel().isActive()) {
                //查询最近100条日志给他看
                String lastData = logService.getLastData(recordId);
                if (lastData != null) {
                    try {
                        ws.send(WebConstConfig.OBJECT_MAPPER.writeValueAsString(new Msg("record", lastData)));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                DataWebSocket.wsMap.remove(recordId);
            }
        }

    }

}
